package com.tianzhu.service;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tianzhu.domain.Authority;
import com.tianzhu.domain.Cart;
import com.tianzhu.domain.Customer;
import com.tianzhu.domain.User;
import com.tianzhu.repositories.AuthorityRepo;
import com.tianzhu.repositories.BillingaddressRepo;
import com.tianzhu.repositories.CartRepo;
import com.tianzhu.repositories.CustomerRepo;
import com.tianzhu.repositories.ShippingaddressRepo;

@Service
@Transactional
@Slf4j
public class CustomerService {
	
	@Autowired
	CustomerRepo customerRepo;
	
	@Autowired
	UserService userSsevice;
	
	@Autowired
	AuthorityRepo authorityRepo;
	
	@Autowired
	CartService cartService;
	
	@Autowired
	PasswordEncoder passwordEncoder;
	
	@Autowired
	ShippingaddressRepo shippingaddressRepo;
	
	@Autowired
	BillingaddressRepo billingaddressRepo;
	
	public Customer addCustomer(Customer customer){
		
		customer.getBillingAddress().setCustomer(customer);
        customer.getShippingAddress().setCustomer(customer);
		
        
        shippingaddressRepo.save(customer.getShippingAddress());
        billingaddressRepo.save(customer.getBillingAddress());
        customer = customerRepo.save(customer);
        
        
        User user =new User();
        user.setUsername(customer.getUsername());
        String password = passwordEncoder.encode(customer.getPassword());
        user.setPassword(password);
        user.setEnabled(1);
        user.setCustomerid(customer.getId());
        user = userSsevice.create(user);
        Authority newAuthorities = new Authority();
        newAuthorities.setUser(user);
        newAuthorities.setAuthority("ROLE_USER");
        authorityRepo.save(newAuthorities);
        
        
        Cart newCart = new Cart();
        newCart.setCustomer(customer);
        customer.setCart(newCart);
        cartService.update(newCart);
		return customerRepo.save(customer);
	}

	public Customer getCustomerById(Long customerId){
    	return customerRepo.findOne(customerId);
    }

	public List<Customer> getAllCustomers(){
    	
    	return customerRepo.findAll();
    }

	public Customer getCustomerByUsername(String username){
    	return customerRepo.findCustomerByUsername(username);
    }

}
